package com.chengxiaoxiao.dao.impl;

import com.chengxiaoxiao.dao.BookDao;
import com.chengxiaoxiao.dao.ReturnsDao;
import com.chengxiaoxiao.dao.UsersDao;
import com.chengxiaoxiao.domain.Books;
import com.chengxiaoxiao.domain.Returns;
import com.chengxiaoxiao.domain.Users;
import com.chengxiaoxiao.utils.db.*;

import java.util.ArrayList;
import java.util.List;

public class ReturnsDaoImpl implements ReturnsDao {
    private DBAssist da = new DBAssist(DBCPUtil.getDataSource());

    private UsersDao usersDao = new UsersDaoImpl();
    private BookDao bookDao = new BookDaoImpl();

    @Override
    public void add(Returns returns) {
        da.update("insert into returns(subTime,userId,bookId,borrowId) values(?,?,?,?)", returns.getSubTime(), returns.getUserId(), returns.getBookId(),returns.getBorrowId());

    }

    @Override
    public void update(Returns returns) {
        da.update("update returns set subTime=?,userId=?,bookId=?,borrowId=? where id=?", returns.getSubTime(), returns.getUserId(), returns.getBookId(),returns.getBorrowId(), returns.getId());
    }

    @Override
    public void delete(long id) {
        da.update("delete from returns where id=?", id);
    }

    @Override
    public List get() {

        List<Returns> list = (List<Returns>) da.query("select * from returns", new BeanListHandler(Returns.class));

        List<Returns> model = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {

            Returns b = list.get(i);
            Users user = usersDao.getbyId(b.getUserId());
            b.setUser(user);
            Books book = bookDao.getbyId(b.getBookId());
            b.setBook(book);
            model.add(b);
        }
        return model;
    }

    @Override
    public Returns getbyId(long id) {
        Returns b = (Returns) da.query("select * from returns", new BeanHandler(Returns.class));

        Users user = usersDao.getbyId(b.getUserId());
        b.setUser(user);
        Books book = bookDao.getbyId(b.getBookId());
        b.setBook(book);

        return b;
    }

    @Override
    public List getListPage(int startIndex, int pageSize) {

        List<Returns> list = (List<Returns>) da.query("select * from returns limit ?,?", new BeanListHandler(Returns.class), startIndex, pageSize);
        List<Returns> model = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {

            Returns b = list.get(i);
            Users user = usersDao.getbyId(b.getUserId());
            b.setUser(user);
            Books book = bookDao.getbyId(b.getBookId());
            b.setBook(book);
            model.add(b);

        }

        return model;
    }

    @Override
    public int getTotalRecordsNum() {

        return (int) da.query("select count(*) from returns", new ScalarHandler());
    }
}
